<template>
  <div class="update-avatar">
    <img :src="imgUrl" ref="img" />
    <div class="toolbar">
      <span @click="$emit('cancel')">取消</span>
      <span @click="onSave">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user.js'
import { Toast } from 'vant'
export default {
  name: 'EditAvarat',
  props: {
    imgUrl: {
      type: String,
      required: true
    }
  },
  data () {
    return {

    }
  },
  mounted () {
    const img = this.$refs.img
    this.cropper = new Cropper(img, {
      aspectRatio: 1 / 1,
      viewMode: 1,
      dragMode: 'move',
      background: false,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false
    })
  },
  // 定义方法
  methods: {
    onSave () {
      // 1. 后端裁剪 把坐标大小发送到服务器进行裁剪
      // console.log(this.cropper.getData())

      // 2. 前端裁剪
      // console.log(this.cropper.getCroppedCanvas())
      // <canvas></canvas> toBlob是canvas的方法
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 后端要的是form-data
        const formData = new FormData()
        formData.append('photo', blob)
        // 将formData交给后端 里面包含了裁剪好的图片
        try {
          const { data: res } = await updateUserAvatar(formData)
          Toast('成功！')
          this.$emit('cancel')
          this.$emit('onSuccess', res.data.photo)
        } catch (err) {
          Toast('失败！')
        }
      })
    }
  }

}
</script>

<style scoped lang='less'>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
